package org.example.sec11.interceptors.server;

import io.grpc.*;

import java.util.Objects;

import static org.example.sec11.Constants.API_KEY;

public class ApiKeyInterceptor implements ServerInterceptor {
    @Override
    public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next) {
        String s = headers.get(API_KEY);
        if (isVaild(s)) {
            return next.startCall(call, headers);
        }
        System.out.println(call.getMethodDescriptor().getServiceName());
        System.out.println(call.getMethodDescriptor().getBareMethodName());
        System.out.println(call.getMethodDescriptor().getFullMethodName());

        call.close(Status.UNAUTHENTICATED.withDescription("client must be api key"),
                headers);
        return new ServerCall.Listener<ReqT>() {
        };
    }

    private boolean isVaild(String apiKey) {
        return Objects.nonNull(apiKey) && "bank-client-pwd1".equals(apiKey);
    }
}
